package com.woniuxy.boot.nb_auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.boot.nb_auth.bean.User;
import com.woniuxy.boot.nb_auth.feign.DistributedIdFeign;
import com.woniuxy.boot.nb_auth.mapper.UserMapper;
import com.woniuxy.boot.nb_auth.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DistributedIdFeign distributedIdFeign;

    /**
     * 根据电话查询回用户信息
     **/
    @Override
    public User getUserByPhone(String phone) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getPhone, phone);
        User user = userMapper.selectOne(lambdaQueryWrapper);
        if (user == null) {
            User enroll = new User();
            enroll.setId(distributedIdFeign.get());
            enroll.setPhone(phone);
            enroll.setRegisterTime(LocalDateTime.now());
            enroll.setStatus("a");
            enroll.setCarNum(0);
            enroll.setName("新用户");
            enroll.setIsBuy("a");
            enroll.setPolicyNum(0L);
            userMapper.insert(enroll);
            return enroll;
        }
        return user;
    }


    @Override
    public void carNumPlusOne(Long id) {
        User user = getUserById(id);
        user.setCarNum(user.getCarNum()+1);
        userMapper.insertOrUpdate(user);
    }

    @Override
    public void policyNumPlusOne(Long id) {
        User user = getUserById(id);
        user.setStatus("b");
        user.setPolicyNum(user.getPolicyNum()+1);
        userMapper.insertOrUpdate(user);
    }

    @Override
    public User getUserById(Long id){
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getId, id);
        return userMapper.selectOne(lambdaQueryWrapper);
    }
}
